//
//  WPPPickerDayTimeView.m
//  LoveIN
//
//  Created by bst on 2019/7/2.
//  Copyright © 2019 bst. All rights reserved.
//

#import "WPPPickerDayTimeView.h"
#define kSelfHeight (287*ADAPTER_WIDTH)
#import "WPPPickerTopView.h"
@interface WPPPickerDayTimeView ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property(nonatomic,strong)UIControl *bgControl;
@property(nonatomic,strong)WPPPickerTopView *topView;
@property(nonatomic,strong)UIPickerView *pickerView;
//数据 包括年 月 日
@property(nonatomic,strong)NSMutableArray<NSMutableArray<NSString *> *> *dataSource;
@property(nonatomic,strong)NSMutableArray<NSString *> *years;
@property(nonatomic,strong)NSMutableArray<NSString *> *months;
@property(nonatomic,strong)NSMutableArray<NSString *> *days;//变化比较大 根据闰年 月份判断普通月份和2月份
//当前的年月日
@property(nonatomic,strong)NSString *year;
@property(nonatomic,strong)NSString *month;
@property(nonatomic,strong)NSString *day;

@property(nonatomic,strong)NSString *currentYear;
@property(nonatomic,strong)NSString *currentMonth;
@property(nonatomic,strong)NSString *currentDay;
@end

@implementation WPPPickerDayTimeView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self createProperty];
        [self createUI];
        [self createDataSource];
        [self startAnimation];
    }
    return self;
}
- (void)dealloc
{
    NSLog(@"WPPPickerCateView---dealloc");
}
- (void)createProperty
{
    self.backgroundColor = [UIColor whiteColor];
    [self.bgControl addSubview:self];
    self.frame = CGRectMake(0, HEIGHT, WIDTH, kSelfHeight);
}
- (void)createUI
{
    [self topView];
    //[self pickerView];
}
- (void)createDataSource
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [formatter stringFromDate:date];
    NSArray<NSString *> *timeArrs = [currentTime componentsSeparatedByString:@"-"];
    self.year = timeArrs[0];
    self.month = [NSString stringWithFormat:@"%ld",timeArrs[1].integerValue];
    self.day = [NSString stringWithFormat:@"%ld",timeArrs[2].integerValue];
    
    self.currentYear = self.year;
    self.currentMonth = self.month;
    self.currentDay = self.day;
    
    [self.dataSource addObject:self.years];
    [self.dataSource addObject:self.months];
    [self.dataSource addObject:self.days];
    [self.pickerView reloadAllComponents];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.pickerView selectRow:[self.years indexOfObject:self.year] inComponent:0 animated:YES];
        [self.pickerView selectRow:[self.months indexOfObject:self.month] inComponent:1 animated:YES];
        [self.pickerView selectRow:[self.days indexOfObject:self.day] inComponent:2 animated:YES];
    });
}
#pragma mark - setter方法
- (void)setParentVC:(BaseVC *)parentVC
{
    _parentVC = parentVC;
    [parentVC.view addSubview:self.bgControl];
}
- (void)setTitle:(NSString *)title
{
    _title = title;
    self.topView.title = title;
}
- (void)setScheduleLimit:(BOOL)scheduleLimit
{
    _scheduleLimit = scheduleLimit;
    if (!scheduleLimit) {
        return;
    }
    _years = [NSMutableArray array];
    for (NSInteger index = 2020; index <= 2025; index ++) {
        [_years addObject:[NSString stringWithFormat:@"%ld",index]];
    }
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:self.years];
    [self.dataSource addObject:self.months];
    [self.dataSource addObject:self.days];
    [self.pickerView reloadAllComponents];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.pickerView selectRow:[self.years indexOfObject:self.year] inComponent:0 animated:YES];
        [self.pickerView selectRow:[self.months indexOfObject:self.month] inComponent:1 animated:YES];
        [self.pickerView selectRow:[self.days indexOfObject:self.day] inComponent:2 animated:YES];
    });
}
#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return self.dataSource.count;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.dataSource[component].count;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 44*ADAPTER_WIDTH;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (view == nil) {
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.width - 100*ADAPTER_WIDTH, 44)];
        lab.font = [UIFont systemFontOfSize:15*ADAPTER_WIDTH weight:UIFontWeightRegular];
        lab.textColor = [UIColor blackColor];
        lab.textAlignment = NSTextAlignmentCenter;
        view = lab;
    }
    UILabel *lab = (UILabel *)view;
    if (component == 0) {
        lab.text = [NSString stringWithFormat:@"%@年",self.dataSource[component][row]];
    } else if (component == 1) {
        lab.text = [NSString stringWithFormat:@"%@月",self.dataSource[component][row]];
    } else {
        lab.text = [NSString stringWithFormat:@"%@日",self.dataSource[component][row]];
    }
    return lab;
}
//点击/滑动非正确位置 会自动滑动上来 或者滑动下去
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.year = self.dataSource[0][[pickerView selectedRowInComponent:0]];
    self.month = self.dataSource[1][[pickerView selectedRowInComponent:1]];
    self.day = self.dataSource[2][[pickerView selectedRowInComponent:2]];
    if (self.scheduleLimit) {
        if (self.year.integerValue < 2020) {
            [self.pickerView selectRow:[self.years indexOfObject:self.currentYear] inComponent:0 animated:YES];
            [self.pickerView selectRow:[self.months indexOfObject:self.currentMonth] inComponent:1 animated:YES];
            [self.pickerView selectRow:[self.days indexOfObject:self.currentDay] inComponent:2 animated:YES];
            return;
        }
        if (self.year.integerValue > 2025) {
            [self.pickerView selectRow:[self.years indexOfObject:self.currentYear] inComponent:0 animated:YES];
            [self.pickerView selectRow:[self.months indexOfObject:self.currentMonth] inComponent:1 animated:YES];
            [self.pickerView selectRow:[self.days indexOfObject:self.currentDay] inComponent:2 animated:YES];
            return;
        }
    }
    if (component == 0 || component == 1) {
        [self.dataSource replaceObjectAtIndex:2 withObject:self.days];
        [pickerView reloadComponent:2];
    }
    /**
     dispatch_async(dispatch_get_main_queue(), ^{
        self.day = self.days[[pickerView selectedRowInComponent:2]];
     });
     */
}
#pragma mark - 点击事件
- (void)clickBgControl:sender
{
    [self endAnimation];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.21 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self removeAllSubviews];
        [self.bgControl removeAllSubviews];
        [self.bgControl removeFromSuperview];
    });
}
- (void)clickSureButton
{
    //[self.pickerView selectRow:4 inComponent:0 animated:YES];
    //[self.pickerView selectRow:1 inComponent:1 animated:YES];
    
    //[self.pickerView reloadAllComponents];
    
    self.year = self.years[[self.pickerView selectedRowInComponent:0]];
    self.month = self.months[[self.pickerView selectedRowInComponent:1]];
    self.day = self.days[[self.pickerView selectedRowInComponent:2]];
    
    !self.backTimesBlock ?: self.backTimesBlock ([NSString stringWithFormat:@"%@-%@-%@",self.year,self.month.integerValue < 10 ? [NSString stringWithFormat:@"0%@",self.month] : self.month,self.day.integerValue < 10 ? [NSString stringWithFormat:@"0%@",self.day] : self.day]);
    [self clickBgControl:nil];
    //self.month.integerValue < 10 ? [NSString stringWithFormat:@"0%@",self.month] : self.month
}
#pragma mark - 动画
- (void)startAnimation
{
    [UIView animateWithDuration:0.2 animations:^{
        self.frame = CGRectMake(0, HEIGHT - kSelfHeight, WIDTH, kSelfHeight);
    }];
}
- (void)endAnimation
{
    [UIView animateWithDuration:0.2 animations:^{
        self.frame = CGRectMake(0, HEIGHT, WIDTH, kSelfHeight);
    }];
}
#pragma mark - Lazy懒加载区域
- (UIControl *)bgControl
{
    if (!_bgControl)
    {
        UIControl *bgControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
        [[UIApplication sharedApplication].keyWindow addSubview:bgControl];
        bgControl.backgroundColor = rgba(0, 0, 0, 0.4);
        [bgControl addTarget:self action:@selector(clickBgControl:) forControlEvents:UIControlEventTouchDown];
        _bgControl = bgControl;
    }
    return _bgControl;
}
- (WPPPickerTopView *)topView
{
    if (!_topView) {
        WPPPickerTopView *view = [[WPPPickerTopView alloc]initWithFrame:CGRectMake(0, 0, self.width, 50*ADAPTER_WIDTH)];
        [self addSubview:view];
        WK(weakSelf)
        [view setCallBackTypeBlock:^(BOOL cancel) {
            if (cancel) {
                [weakSelf clickBgControl:nil];
            } else {
                [weakSelf clickSureButton];
            }
        }];
        _topView = view;
    }
    return _topView;
}
- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        UIPickerView *view = [[UIPickerView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, WIDTH, self.height - self.topView.height)];
        view.delegate = self;
        view.dataSource = self;
        view.showsSelectionIndicator = YES;
        view.backgroundColor = [UIColor whiteColor];
        [self addSubview:view];
        _pickerView = view;
    }
    return _pickerView;
}
- (NSMutableArray<NSMutableArray<NSString *> *> *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (NSMutableArray<NSString *> *)years
{
    if (!_years) {
        _years = [NSMutableArray array];
        for (NSInteger index = 1970; index <= 2099; index ++) {
            [_years addObject:[NSString stringWithFormat:@"%ld",index]];
        }
    }
    return _years;
}
- (NSMutableArray<NSString *> *)months
{
    if (!_months) {
        _months = [NSMutableArray array];
        for (NSInteger index = 1; index <= 12; index ++) {
            [_months addObject:[NSString stringWithFormat:@"%ld",index]];
        }
    }
    return _months;
}
- (NSMutableArray<NSString *> *)days
{
    NSMutableArray<NSNumber *> *months = [NSMutableArray array];
    [months addObjectsFromArray:@[@31,@28,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31]];
    //判断2月
    NSInteger year = self.year.integerValue;
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        [months replaceObjectAtIndex:1 withObject:@29];
    }
    //获取天数
    NSInteger dayNum = months[(self.month.integerValue - 1)].integerValue;
    NSMutableArray *day = [NSMutableArray array];
    for (NSInteger index = 1; index <= dayNum; index ++) {
        [day addObject:[NSString stringWithFormat:@"%ld",index]];
    }
    return day;
}
@end
